package com.yn.sys.tools;

import com.alibaba.fastjson2.JSONArray;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

@Slf4j
public class FileUtils {

    private static String pathStr = System.getProperty("user.dir") + File.separator +"config";
    public static JSONArray readFileToJson(){
        File dir = new File(pathStr);
        File[] files = dir.listFiles();
        if (files == null) {
            log.error("{} File dir is null ", pathStr);
            return new JSONArray();
        }

        for (File file : files) {
            if (file.isDirectory()) {
                continue;
            }
            if (!StringUtils.endsWith(file.getName(), ".json")) {
                continue;
            }
            log.info("load file name is {}", file.getName());
            // 读取文件
            try {
                String jsonString = new String(Files.readAllBytes(Paths.get(file.getPath())));
                return JSONArray.parseArray(jsonString);
            } catch (IOException e) {
                log.error("IOException {}, {}", file.getName(), e);
            }
        }
        return new JSONArray();
    }
}
